<template>
  <tbc-dialog ref="dialog" title="快速编辑" @confirm="formSubmit">
    <tbc-dynamic-form :form="dynamicForm" class="compact"/>
  </tbc-dialog>
</template>
<script lang="ts">
import {defineComponent, reactive, toRefs, ref, Ref} from 'vue'
import http from '@/plugin/http'
import {ElMessage} from 'element-plus'

export default defineComponent({

  name: 'goods-quick-edit',

  setup(props, {emit}) {
    const dialog: Ref = ref(null)
    const state = reactive({
      form: {goods_id: ''},
      dynamicForm: [
        {label: '商品ID', type: 'hidden', field: 'goods_id', value: ''},
        {label: '商品名称', type: 'input', field: 'goods_name', value: ''},
        {label: '排序', type: 'input-number', field: 'sort_weight', value: ''},
        {
          label: '销售状态', type: 'radio', field: 'sale_status', value: '', options: [
            {label: '上架', value: 1},
            {label: '下架', value: 2},
          ]
        },
      ]
    })

    const show = (data: Record<string, number | string>): void => {
      dialog.value.show()
      state.dynamicForm.forEach(item => {
        if (typeof data[item.field] !== 'undefined') {
          item.value = data[item.field] as string
        }
      })
    }

    const formSubmit = async () => {
      let form: Record<string, string | number> = {}
      state.dynamicForm.forEach(item => form[item.field] = item.value)
      const res = await http.post('/goods/quickEdit', form)
      if (res.data.code !== 0) return ElMessage.error(res.data.message);
      ElMessage.success(res.data.message);
      emit('success')
      dialog.value.close()
    }

    return {
      ...toRefs(state),
      dialog,
      show,
      formSubmit
    }
  }
})
</script>